package com.message.Volcengine_ai_API.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Iterator;
import java.util.List;

public class Base64Util {

    @Value("${external.resource.dir}")
    private String externalResourceDir;
@Test
public static void main(String[] args) throws IOException {
    // 输入文本文件路径
    Path inputPath = Paths.get("./external-resources/新建文本文档.txt");
    // 输出图片文件路径
    Path outputPath = Paths.get("./external-resources/external-resources.png");

    try {
        // 读取Base64编码的字符串
        String base64Image = new String(Files.readAllBytes(inputPath));

        // 如果Base64字符串包含数据URI scheme（如"data:image/png;base64,"），需要去掉这部分
        if (base64Image.contains(",")) {
            base64Image = base64Image.substring(base64Image.indexOf(",") + 1);
        }

        // 解码Base64字符串到字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);

        // 将字节数组写入PNG文件
        Files.write(outputPath, imageBytes);

        System.out.println("成功将Base64编码转换为PNG图像: " + outputPath.toAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println("转换过程中出错: " + e.getMessage());
    }
}
    public static String imageToBase64(File file) throws IOException {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            fileInputStream.read(bytes);
            return Base64.getEncoder().encodeToString(bytes);
        }
    }
    public static void Base64ToImage(List<String> list,String externalResourceDir) throws IOException {
        // 将非法字符替换为合法字符
        String name = LocalTime.now().toString().replace(':', '-');
// 构建文件路径，使用File.separator以确保跨平台兼容性
        String outputFilePath = "./external-resources/" + name + ".txt";
        // 将image属性写入文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputFilePath)))) {
            //writer.write(outputFilePath);
            writer.write(list.get(0));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        // 输入 Base64 编码文件的路径
        String outputImagePath =externalResourceDir+"\\"+name+".png";
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(outputFilePath))) {
            StringBuilder base64StringBuilder = new StringBuilder();
            char[] buffer = new char[1024]; // 用于读取文件的缓冲区
            int bytesRead;

            // 按块读取 Base64 编码文件
            while ((bytesRead = reader.read(buffer)) != -1) {
                base64StringBuilder.append(buffer, 0, bytesRead);
            }
            String base64String = base64StringBuilder.toString();
            try {
                byte[] imageBytes = Base64.getDecoder().decode(base64String);
                try (FileOutputStream fos = new FileOutputStream(outputImagePath)) {
                    fos.write(imageBytes);
                    System.out.println("图像已成功保存到 " + outputImagePath);
                }
            } catch (IllegalArgumentException e) {
                System.err.println("解码失败，可能是因为数据不完整或格式错误: " + e.getMessage());
            }
        }
        catch (IOException e) {
            e.printStackTrace();
            System.err.println("读取或写入文件时出错: " + e.getMessage());
        }
        finally {
            outputFilePath =externalResourceDir+"\\"+name+".txt";
            // 创建 Path 对象
            Path path = Paths.get(outputFilePath);
            // 检查文件是否存在
            if (Files.exists(path)) {
                // 尝试删除文件
                Files.delete(path);
            } else {
            }
        }
    }

}
